<?php
	$cur_page_ver="0.5d";
	//echo $_SESSION['last_page'];
	$this_page="login";
	$this_title="Login";
	$center_main=true;
	require_once('includes/global.php');
	if(isset($_GET['action']))
	{
		//echo 'action is set\n';
		if($_GET['action']=='logout')
		{
			//echo 'action = logout';
			$smarty->assign('last_page',$_SESSION['last_page'].'.php');
			session_destroy();
			$smarty->display('redirect.tpl');
		}
	}
	else if(isset($_POST['username']) && isset($_POST['userpass']))
	{
		$result=$dbcon->query("select UID from users where UN='".$_POST['username']."' and PW='".sha1($_POST['userpass'])."'",2);
		if($result)
		{
			$_SESSION['logged_as_user']=$_POST['username'];
			$_SESSION['uid']=$result[0];
			$smarty->assign('last_page',$_SESSION['last_page'].'.php');
			$smarty->display('redirect.tpl');
		}
		else
		{
			$result=$dbcon->query("select UID from users where UN='".$_POST['username']."' and PW='".md5($_POST['userpass'])."'",2);
			if($result)
			{
				$_SESSION['logged_as_user']=$_POST['username'];
				$_SESSION['uid']=$result[0];
				$dbcon->executeSQL("UPDATE `users` SET `PW`='".sha1($_POST['userpass'])."' WHERE UID=".$_SESSION['uid']);
				$smarty->assign('last_page',$_SESSION['last_page'].'.php');
				$smarty->display('redirect.tpl');
			}
			else
			{
				$smarty->assign('login_error',true);
				$smarty->display('header.tpl');
				$smarty->display('login.tpl');
				$smarty->display('footer.tpl');
			}
		}
	}
	else
	{
		$smarty->display('header.tpl');
		$smarty->display('login.tpl');
		$smarty->display('footer.tpl');
	}
?>